package com.sshiro.captcha;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sshiro.util.SpringUtil;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

public class KaptchaServlet extends com.google.code.kaptcha.servlet.KaptchaServlet {

	private static final long serialVersionUID = 3135861912266060554L;

	private Producer kaptchaProducer = null;
	
	@Override
	public void init(ServletConfig conf) throws ServletException {
		super.init(conf);
		kaptchaProducer = SpringUtil.getBean(Producer.class, null);
	}
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// Set to expire far in the past.
		resp.setDateHeader("Expires", 0);
		// Set standard HTTP/1.1 no-cache headers.
		resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		resp.setHeader("Pragma", "no-cache");

		// return a jpeg
		resp.setContentType("image/jpeg");

		// create the text for the image
		String capText = this.kaptchaProducer.createText();

		// store the text in the session
		req.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

		// store the date in the session so that it can be compared
		// against to make sure someone hasn't taken too long to enter
		// their kaptcha
		req.getSession().setAttribute(Constants.KAPTCHA_SESSION_DATE, new Date());

		// create the image with the text
		BufferedImage bi = this.kaptchaProducer.createImage(capText);
		
		ServletOutputStream out = resp.getOutputStream();

		// write the data out
		ImageIO.write(bi, "jpg", out);
	}
	
}
